<?php
	
    /**
     * Apologizes to user with message.
     */
	 
	
    function apologize($message)
    {
        render("apology.php", array("message" => $message));
        exit;
    }
    
    function check_in_range($start_date, $end_date, $date_from_user)
    {
      // Convert to timestamp
      $start_ts = strtotime($start_date);
      $end_ts = strtotime($end_date);
      $user_ts = strtotime($date_from_user);

      // Check that user date is between start & end
      return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
    }
    
    function string_trim($string, $trimLength = 40) 
    {
      $length = strlen($string);
      mb_internal_encoding("UTF-8");
      if ($length > $trimLength) {
          $count = 0;
          $prevCount = 0;
          $array = explode(" ", $string);
          foreach ($array as $word) {
              $count = $count + strlen($word);
              $count = $count + 1;
              if ($count > ($trimLength - 3)) {
                  return mb_substr($string, 0, $prevCount) . "...";
              }
              $prevCount = $count;
          }
      } else {
          return $string;
      }
  }
    /**
     * Facilitates debugging by dumping contents of variable
     * to browser.
     */
    function dump($variable)
    {
        require("templates/dump.php");

        exit;
    }


    
    /**
     * Returns a stock by symbol (case-insensitively) else false if not found.
    
    function lookup($symbol)
    {
        // reject symbols that start with ^
        if (preg_match("/^\^/", $symbol))
        {
            return false;
        }

        // reject symbols that contain commas
        if (preg_match("/,/", $symbol))
        {
            return false;
        }

        // open connection to Yahoo
        $handle = @fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s=$symbol", "r");
        if ($handle === false)
        {
            return false;
        }

        // download first line of CSV file
        $data = fgetcsv($handle);
        if ($data === false || count($data) == 1)
        {
            return false;
        }

        // close connection to Yahoo
        fclose($handle);

        // ensure symbol was found
        if ($data[2] === "0.00")
        {
            return false;
        }

        // return stock as an associate array
        return [
            "symbol" => $data[0],
            "name" => $data[1],
            "price" => $data[2],
        ];
    }
	*/
    /**
     * Executes SQL statement, possibly with parameters, returning
     * an array of all rows in result set or false on (non-fatal) error.
     */
    function query(/* $sql [, ... ] */)
    {
      
        // SQL statement
        $sql = func_get_arg(0);
      
        // parameters, if any
        $parameters = array_slice(func_get_args(), 1);
        if(isset($parameters[0]) && is_array($parameters[0]))
        {
          $parameter2 = array_slice($parameters[0], 0);
         
        }
        // try to connect to database
        static $handle;
        if (!isset($handle))
        {
		
            try
            {
                // connect to database
                $handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD,array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

                // ensure that PDO::prepare returns false when passed invalid SQL
                $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
			
            }
            catch (Exception $e)
            {
                // trigger (big, orange) error
                trigger_error($e->getMessage(), E_USER_ERROR);
                exit;
            }
        }
        // prepare SQL statement
        if($sql == "getlastid") 
          return  $handle->lastInsertId();
        else
          $statement = $handle->prepare($sql);
        
        if ($statement === false)
        {
            // trigger (big, orange) error
            
            exit;
        }
			
		if(isset($parameters[1]) && $parameters[1] === "like")
			$results = $statement->execute(array("%$parameters[0]%"));
			
		else {
      if(isset($parameter2)) //passing array of arrays
      {
        $i=0;
        foreach($parameter2 as $para){
           if(is_array($para)) //in account for multi categories
           {
            foreach($para as $element)
            {
             $statement->bindValue(++$i, $element);
            }
           }
           else
           {
             $statement->bindValue(++$i, $para);
           }
        }
        $results = $statement->execute();
      }
      else
      {
			// execute SQL statement-- genreal case
        $results = $statement->execute($parameters);
      }
		}
      // return result set's rows, if any
        
        if ($results !== false )
        {
			
            return $statement->fetchAll(PDO::FETCH_ASSOC);
        }
        else
        {
		
            return false;
        }
    }

    /**
     * Redirects user to destination, which can be
     * a URL or a relative path on the local host.
     */
    function redirect($destination)
    {
        // handle URL
        if (preg_match("/^https?:\/\//", $destination))
        {
            header("Location: " . $destination);
        }

        // handle absolute path
        else if (preg_match("/^\//", $destination))
        {
            $protocol = (isset($_SERVER["HTTPS"])) ? "https" : "http";
            $host = $_SERVER["HTTP_HOST"];
            header("Location: $protocol://$host$destination");
        }

        // handle relative path
        else
        {
            // adapted from http://www.php.net/header
            $protocol = (isset($_SERVER["HTTPS"])) ? "https" : "http";
            $host = $_SERVER["HTTP_HOST"];
            $path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\");
            header("Location: $protocol://$host$path/$destination");
        }

        // exit immediately since we're redirecting anyway
        exit;
    }
    
    

    /**
     * Renders template, passing in values.
     */
    function render($template, $values)
    {
        // if template exists, render it
        if (file_exists("templates/$template"))
        {
            // extract variables into local scope
            extract($values);

            // render header
            require("templates/header.php");

            // render template
            require("templates/$template");

            // render footer
            require("templates/footer.php");
        }

        // else err
        else
        {
            trigger_error("Invalid template: $template", E_USER_ERROR);
        }
    }
	
	function detectEnglish($char)
	{
		$letters = array('a','b','c','d','e','f','g','h',
					'i','j','k','l','m','n','o','p',
					'q','r','s','t','u','v','w','x','y','z');
					
		foreach($letters as $letter) {

			if($char === $letter){
				return 1;
			}
		}
		return 0;
	
	}
	//returning 2D array, each 1D array has cat_id and cat_name
	function getAllCategories()
	{
		$rows = query("SELECT * FROM category ORDER BY cat_name");		   
		return $rows;
	}
  
  function getAllLibraries()
  {
		$rows = query("SELECT * FROM libraries");		   
		return $rows;
	}
	
?>

